package com.zzzzzz.account.reset;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zzzzzz.account.Constants;
import com.zzzzzz.account.EmailSend;
import com.zzzzzz.account.MailService;
import com.zzzzzz.account.ticket.ExpiredTicketException;
import com.zzzzzz.account.ticket.NoSuchTicketException;
import com.zzzzzz.account.ticket.Ticket;
import com.zzzzzz.account.ticket.TicketDao;
import com.zzzzzz.account.user.NoSuchUserException;
import com.zzzzzz.account.user.User;
import com.zzzzzz.account.user.UserDao;

@Service("resetPasswordService")
public class ResetPasswordServiceImpl implements ResetPasswordService {
	
	@Resource
	private UserDao userDao;
	@Resource
	private TicketDao ticketService;
	@Resource
	private MailService mailService;
	
	public void sendResetMail(String email) throws NoSuchUserException {
		User user = userDao.findByEmail(email);
		Ticket ticket = ticketService.add(user.getId(), Constants.TICKET_TYPE.PASSWORD_RESET);
		String resetPasswordURL = "/account/reset_password/" + ticket.getKey();
		System.out.println("resend password url: " + resetPasswordURL);

		// send reset password email
		EmailSend emailSend = new EmailSend();
		emailSend.setSendTo(user.getEmail());
		emailSend.setSendFrom(EmailSend.DEFAULT_SENDTO);
		emailSend.setSubject(EmailSend.REGISTER_ACTIVATE_SUBJECT);
		emailSend.setHtmlTemplate(EmailSend.TEMPLATE.RESET_PASSWORD_TEMPLATE);
		Map<String,Object> htmlData = new HashMap<String,Object>();
		htmlData.put("reset_password_url", resetPasswordURL);
		emailSend.setHtmlData(htmlData);
		mailService.sendMail(emailSend);
	}
	
	public void changePassword(String token, String password) throws NoSuchTicketException, ExpiredTicketException {
		Long userId = ticketService.findClassPKByKey(token, Constants.TICKET_TYPE.PASSWORD_RESET);
		userDao.editPassword(userId, password);
		ticketService.delByKey(token);
	}

	public boolean isValidResetToken(String token) {
		try {
			ticketService.findClassPKByKey(token, Constants.TICKET_TYPE.PASSWORD_RESET);
		} catch (NoSuchTicketException e) {
			return false;
		} catch (ExpiredTicketException e) {
			return false;
		}
		return true;
	}
	

}
